<template>
  <div class="review-container">
    <!-- 评价表单卡片 -->
    <el-card class="review-card" v-if="route.name === 'AddReview' && selectedBooking">
      <template #header>
        <div class="card-header">
          <h2>发表评价</h2>
        </div>
      </template>

      <el-form :model="reviewForm" :rules="rules" ref="reviewFormRef" label-width="100px">
        <div class="booking-info">
          <h4>{{ hotelName }} - {{ roomType }}</h4>
          <p>入住时间: {{ formatDate(selectedBooking.checkInDate) }} 至 {{ formatDate(selectedBooking.checkOutDate) }}</p>
        </div>
        
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="reviewForm.rating" :max="5" />
        </el-form-item>
        
        <el-form-item label="评价内容" prop="comment">
          <el-input 
            type="textarea" 
            v-model="reviewForm.comment" 
            placeholder="请分享您的入住体验..." 
            :rows="4"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitReview">提交评价</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 我的评价列表 -->
    <el-card class="review-list-card" v-if="route.name === 'MyReviews'">
      <template #header>
        <div class="card-header">
          <h3>我的评价</h3>
        </div>
      </template>

      <div v-if="reviewList.length > 0">
        <div class="review-item" v-for="review in reviewList" :key="review.id">
          <div class="review-header">
            <div>
              <h4>{{ review.hotelName }}</h4>
              <p>{{ review.roomType }}</p>
            </div>
            <el-rate v-model="review.rating" disabled />
          </div>
          
          <div class="review-content">
            <p>{{ review.comment }}</p>
            <div class="review-time">{{ formatDateTime(review.reviewTime) }}</div>
          </div>
          
          <!-- 酒店回复 -->
          <div class="review-reply" v-if="review.reply">
            <div class="reply-title">酒店回复:</div>
            <div class="reply-content">
              <p>{{ review.reply }}</p>
              <div class="reply-time">{{ formatDateTime(review.replyTime) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <el-empty v-else description="暂无评价记录"></el-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request.js';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const reviewFormRef = ref(null);
const selectedBooking = ref(null);
const hotelName = ref('');
const roomType = ref('');
const reviewList = ref([]);

// 评价表单
const reviewForm = ref({
  bookingId: null,
  userId: null,
  hotelId: null,
  roomId: null,
  rating: 5,
  comment: ''
});

// 表单验证规则
const rules = {
  rating: [{ required: true, message: '请给出评分', trigger: 'change' }],
  comment: [
    { required: true, message: '请填写评价内容', trigger: 'blur' },
    { min: 5, max: 500, message: '评价内容长度应在5-500个字符之间', trigger: 'blur' }
  ]
};

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString();
};

// 日期时间格式化
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return date.toLocaleString();
};

// 加载预订信息
const loadBookingInfo = async () => {
  if (route.name !== 'AddReview') return;
  
  const bookingId = route.params.bookingId;
  if (!bookingId) {
    ElMessage.error('未找到预订信息');
    return;
  }
  
  try {
    // 获取预订信息
    const bookingRes = await request.get(`/booking/selectById/${bookingId}`);
    selectedBooking.value = bookingRes.data;
    
    // 初始化评价表单
    reviewForm.value.bookingId = selectedBooking.value.id;
    reviewForm.value.hotelId = selectedBooking.value.hotelId;
    reviewForm.value.roomId = selectedBooking.value.roomId;
    
    // 获取当前登录用户信息
    const userStr = localStorage.getItem('xm-pro-user');
    if (userStr) {
      const user = JSON.parse(userStr);
      reviewForm.value.userId = user.id;
    }
    
    // 获取酒店名称和房间类型
    if (selectedBooking.value.hotelId) {
      const hotelRes = await request.get(`/hotel/selectById/${selectedBooking.value.hotelId}`);
      hotelName.value = hotelRes.data.name || '';
    }
    
    if (selectedBooking.value.roomId) {
      const roomRes = await request.get(`/room/selectById/${selectedBooking.value.roomId}`);
      roomType.value = roomRes.data.roomType || '';
    }
    
  } catch (error) {
    console.error('加载预订信息失败', error);
    ElMessage.error('加载预订信息失败，请稍后重试');
  }
};

// 加载用户的所有评价
const loadUserReviews = async () => {
  if (route.name !== 'MyReviews') return;
  
  try {
    const userStr = localStorage.getItem('xm-pro-user');
    if (!userStr) {
      router.push('/login');
      return;
    }
    
    const user = JSON.parse(userStr);
    const reviewRes = await request.get(`/review/selectByUserId/${user.id}`);
    reviewList.value = reviewRes.data || [];
    
  } catch (error) {
    console.error('加载评价列表失败', error);
    ElMessage.error('加载评价列表失败，请稍后重试');
  }
};

// 提交评价
const submitReview = async () => {
  if (!reviewFormRef.value) return;
  
  await reviewFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      await request.post('/review/add', reviewForm.value);
      ElMessage.success('评价提交成功');
      router.push('/front/booking-records');
    } catch (error) {
      console.error('评价提交失败', error);
      ElMessage.error('评价提交失败，请稍后重试');
    }
  });
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 初始化数据
onMounted(() => {
  loadBookingInfo();
  loadUserReviews();
});
</script>

<style scoped>
.review-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.review-card, .review-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.booking-info {
  margin-bottom: 20px;
  padding: 10px 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.booking-info h4 {
  margin: 0 0 10px 0;
}

.booking-info p {
  margin: 0;
  color: #606266;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.review-header h4 {
  margin: 0 0 5px 0;
}

.review-header p {
  margin: 0;
  color: #606266;
  font-size: 13px;
}

.review-content {
  margin-bottom: 10px;
}

.review-content p {
  margin: 0 0 5px 0;
}

.review-time, .reply-time {
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.review-reply {
  background-color: #f5f7fa;
  padding: 10px;
  margin-top: 10px;
  border-radius: 4px;
}

.reply-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #409EFF;
}

.reply-content p {
  margin: 0 0 5px 0;
}
</style> 